# 使用pyautogui进行键鼠操作
import json
import time
import pyautogui
import os
from pathlib import Path
from loguru import logger

def load_stock_codes():
    """从JSON文件中加载股票代码列表"""
    # 获取项目根目录
    project_root = Path(__file__).parent.parent.parent
    json_file = project_root / "data" / "result0.json"
    
    with open(json_file, 'r', encoding='utf-8') as f:
        data = json.load(f)
    
    return data.get("stock_meet_all", [])

def perform_stock_operation(stock_code):
    """对单个股票代码执行操作"""
    logger.info(f"正在处理股票代码: {stock_code}")
    
    # 提取前6位数字
    stock_number = stock_code[:6]
    
    # 鼠标移动到指定位置并点击
    pyautogui.moveTo(2698, 16)
    pyautogui.click()
    time.sleep(0.1)
    
    # 输入股票代码前6位
    pyautogui.typewrite(stock_number, interval=0.05)
    pyautogui.press('enter')
    time.sleep(4)
    
    # 输入34并按回车
    pyautogui.typewrite('34', interval=0.05)
    pyautogui.press('enter')
    time.sleep(0.1)

    pyautogui.moveTo(2348,555)
    pyautogui.click()
    time.sleep(0.1)
    
    # 再次按回车
    pyautogui.press('enter')
    time.sleep(0.1)
    
    # 按ESC
    pyautogui.press('esc')
    time.sleep(0.1)
    
    logger.info(f"完成处理股票代码: {stock_code}")

def main():
    """主函数"""
    logger.info("开始自动化股票操作...")
    
    # 设置pyautogui的安全设置
    pyautogui.FAILSAFE = True  # 鼠标移动到左上角可以中断程序
    pyautogui.PAUSE = 0.1  # 每个操作之间的默认暂停时间
    
    try:
        # 加载股票代码
        stock_codes = load_stock_codes()
        logger.info(f"共加载到 {len(stock_codes)} 个股票代码")
        
        # 给用户一些时间准备
        logger.info("程序将在5秒后开始执行，请确保目标窗口处于活动状态...")
        time.sleep(5)
        
        # 遍历所有股票代码
        for i, stock_code in enumerate(stock_codes, 1):
            logger.info(f"进度: {i}/{len(stock_codes)}")
            perform_stock_operation(stock_code)
            
            # 每处理10个股票后稍作休息
            if i % 10 == 0:
                logger.info(f"已处理 {i} 个股票，休息2秒...")
                time.sleep(2)
        
        logger.success("所有股票处理完成！")
        
    except KeyboardInterrupt:
        logger.warning("程序被用户中断")
    except Exception as e:
        logger.error(f"程序执行出错: {e}")

if __name__ == "__main__":
    main()